package poradnik.medyczny.UI;

import java.io.IOException;
import java.net.MalformedURLException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import poradnik.medyczny.DB.DBAdapter;
import poradnik.medyczny.Helpers.Connection;
import poradnik.medyczny.Model.Disease;
import poradnik.medyczny.Model.Likehood;
import poradnik.medyczny.Model.Localization;
import poradnik.medyczny.Model.Symptom;
import poradnik.medyczny.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainMenuActivity extends ActionBarBaseActivty {

	// SqlConnector sqlconnector = new SqlConnector();
	DBAdapter medical_db = new DBAdapter(this);

	@SuppressWarnings("static-access")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_menu);

		Button button_search_illness = (Button) findViewById(R.id.button_search_illness);
		Button button_history = (Button) findViewById(R.id.button_history);
		Button button_update = (Button) findViewById(R.id.button_update);
		Button button_help = (Button) findViewById(R.id.button_help);

		button_search_illness.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				if (prefs.getBoolean(Connection.NEEDS_UPDATE, true)) {
					new UpdateTask(MainMenuActivity.this, true).execute();
					prefs.edit().putBoolean(Connection.NEEDS_UPDATE, false).commit();
				} else {
					Intent intent = new Intent(MainMenuActivity.this, MedicalAdviseActivity.class);
					startActivity(intent);
				}

			}

		});

		button_history.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				Intent intent = new Intent(MainMenuActivity.this, AdviseHistoryActivity.class);// GameScreen.class);
				startActivity(intent);
			}

		});

		button_update.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				new UpdateTask(MainMenuActivity.this, false).execute();
			}

		});

		button_help.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {

				new AlertDialog.Builder(MainMenuActivity.this)
				// .setTitle("Droga do " + restaurant.getName())
						.setMessage("cos")// urlString)
						.setIcon(R.drawable.info).setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialoginterface, int i) {

								// finish();
							}
						}).show();

			}

		});

		setUpActionBar("Mobilny Medyk");

	}

	@Override
	protected void onResume() {
		super.onResume();
		try {

			medical_db.createDataBase();

		} catch (IOException ioe) {

			throw new Error("Unable to create database");

		}

		medical_db.openDataBase();
		Cursor p = medical_db.getAllDiseases();

		TextView tv1 = (TextView) findViewById(R.id.textView1);
		if (p != null)
			tv1.setText(p.getCount() + "");
		else
			tv1.setText("0");
		medical_db.close();
	}

	private class UpdateTask extends AsyncTask<Void, Void, Boolean> {
		private ProgressDialog dialog;
		private Context context;
		private boolean startMedicalAdvise;

		protected void onPreExecute() {
			dialog.setMessage("Aktualizacja danych");
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			dialog.show();
		}

		public UpdateTask(Context context, boolean startMedicalAdvise) {
			dialog = new ProgressDialog(context);
			this.context = context;
			this.startMedicalAdvise = startMedicalAdvise;
		}

		protected Boolean doInBackground(Void... urls) {
			DBAdapter db = new DBAdapter(context);
			try {
				db.openDataBase();
				db.clearDB();
				db.close();
			} catch (Exception e) {
				db.close();
			}
			try {

				String temp = Connection.ResponseToString(Connection.fetch("http://sonykuba.lh.pl/gps/syncdata.php"));
				JSONObject everything = new JSONObject(temp);
				JSONArray diseaseArray = new JSONArray(everything.getString(DBAdapter.TABLE_DISEASES));
				JSONArray tempArray = diseaseArray.getJSONArray(0);
				for (int i = 0; i < tempArray.length(); i++) {
					Disease item = Disease.parseJSON(tempArray.getJSONObject(i));
					item.Save(context);
				}
				JSONArray localizationArray = new JSONArray(everything.getString(DBAdapter.TABLE_LOCALIZATIONS));
				tempArray = localizationArray.getJSONArray(0);

				for (int i = 0; i < tempArray.length(); i++) {
					Localization item = Localization.parseJSON(tempArray.getJSONObject(i));
					item.Save(context);
				}
				JSONArray symptomsArray = new JSONArray(everything.getString(DBAdapter.TABLE_SYMPTOMS));
				tempArray = symptomsArray.getJSONArray(0);

				for (int i = 0; i < tempArray.length(); i++) {
					Symptom item = Symptom.parseJSON(tempArray.getJSONObject(i));
					item.Save(context);
				}
				JSONArray locDisArray = new JSONArray(everything.getString(DBAdapter.TABLE_LOCALIZATION_DISEASE_LIKEHOODS));
				tempArray = locDisArray.getJSONArray(0);

				for (int i = 0; i < tempArray.length(); i++) {
					Likehood item = Likehood.parseJSON(tempArray.getJSONObject(i), DBAdapter.tables.LocalizationDiseaseLikehoods);
					item.Save(context, DBAdapter.tables.LocalizationDiseaseLikehoods);
				}
				JSONArray symDisArray = new JSONArray(everything.getString(DBAdapter.TABLE_SYMPTOM_DISEASE_LIKEHOODS));
				tempArray = symDisArray.getJSONArray(0);

				for (int i = 0; i < tempArray.length(); i++) {
					Likehood item = Likehood.parseJSON(tempArray.getJSONObject(i), DBAdapter.tables.SymptomDiseaseLikehoods);
					item.Save(context, DBAdapter.tables.SymptomDiseaseLikehoods);
				}
				JSONArray symLocArray = new JSONArray(everything.getString(DBAdapter.TABLE_SYMPTOM_LOCALIZATION_LIKEHOODS));
				tempArray = symLocArray.getJSONArray(0);

				for (int i = 0; i < tempArray.length(); i++) {
					Likehood item = Likehood.parseJSON(tempArray.getJSONObject(i), DBAdapter.tables.SymptomLocalizationLikehoods);
					item.Save(context, DBAdapter.tables.SymptomLocalizationLikehoods);
				}
				return true;
			} catch (MalformedURLException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} catch (JSONException e) {
				e.printStackTrace();
				return false;
			}
		}

		protected void onPostExecute(Boolean result) {
			try {
				if (dialog.isShowing())
					dialog.dismiss();
			} catch (Exception e) {
			}
			// update view
			if (result) {
				// successful update
				prefs.edit().putBoolean(Connection.NEEDS_UPDATE, false).commit();
				Toast.makeText(context, "Udana aktulizacja", Toast.LENGTH_SHORT).show();
				if (startMedicalAdvise) {
					Intent intent = new Intent(MainMenuActivity.this, MedicalAdviseActivity.class);
					startActivity(intent);
				}
			} else {
				// failure during update
				Toast.makeText(context, "Nie udana aktulizacja", Toast.LENGTH_SHORT).show();
			}
		}

	}
}
